<template>
  <ul class="pug-tree">
    <li v-for="(item) in treeNodes" :key="item.id">
      <div>
           <span @click="expandChildren(item)" class="pug-iconam" v-if="item.children && item.children.length > 0"><span
             v-if="!item.expand"><i class="iconfont icon-zhankai"></i></span>
             <span v-else><i class="iconfont icon-zhankai1"></i></span></span>
        <span class="pug-chk"><input class="pug-checkbox" :checked="item.checked" @change.stop="selectNode(item,$event)" type="checkbox"></span>
        <span class="pug-tit" @click="expandChildren(item)">{{ item.name }}({{ item.children.length }})</span>
      </div>
      <pug-tree-list v-show='item.expand' v-if="item.children && item.children.length > 0"
                     :treeNodes='item.children' :check-ids="checkedids" @select="checkedEventProxy"></pug-tree-list>
    </li>
  </ul>
</template>

<script>
export default {
  name: "PugTreeList",
  props: {
    checkIds:{
      type: Array,
      default:[]
    },
    treeNodes: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      checkedids:[],
      selectNodes: []
    }
  },

  created() {
    this.checkedids = this.checkIds;
  },
  methods: {
    checkedEventProxy(ids,item,flag){
      this.$emit("select",ids,item,flag)
    },

    expandChildren(item) {
      item.expand = !item.expand;
    },

    selectNode(item, ev) {
      if (ev.target.checked) {
        var sindex = this.checkIds.findIndex(res => res == item.id);
        if(sindex == -1) {
          this.checkIds.push(item.id);
        }
        this.$emit("select",this.checkIds,item,true);
      } else {
        var sindex = this.checkIds.findIndex(res => res == item.id);
        this.checkIds.splice(sindex,1);
        this.$emit("select",this.checkIds,item,false);
      }
    }
  }

}
</script>

<style scoped>
.pug-tree {
}

.pug-tree ul {
  margin-left: 20px;
  border-left: 2px dotted #ccc;
  padding-left: 10px
}

.pug-tree .pug-checkbox {
  vertical-align: inherit;
  padding-right: 4px;
}

.pug-tree li {
  padding: 3px 0
}

.pug-tree .pug-iconam {
  position: relative;
  top: 2px;
}

.pug-tree .pug-chk {
  position: relative;
  top: -1px;
  left: 4px;
}

.pug-tree .pug-tit {
  padding-left: 6px
}
</style>
